import { defineComponent, toRefs } from "vue";
import { treeProps, TreeProps } from "./tree-types";

import IconClose from "./components/icon-close";
import IconOpen from "./components/icon-open";
import "./tree.scss";

export default defineComponent({
  name: "gzTree",
  props: treeProps,
  emits: [],
  setup(props: TreeProps, ctx) {
    // const { data } = toRefs(props);
    // 只渲染展开的节点
    // 递归拿到需要渲染的节点
    const openedTree = (tree) => {
      return tree.reduce((pre, item) => {
        return item.open
          ? pre.concat(item, openedTree(item.children))
          : pre.concat(item);
      }, []);
    };

    let openedData = openedTree(props.data);

    console.log(openedData, "openedData");

    const toggle = (item) => {
      console.log(item);
      if (!item.children) {
        return;
      }
      item.open = !item.open;
      openedData = openedTree(props.data);
    };
    const indent = () => <span class="indent"></span>;
    const renderNode = (item) => (
      <div
        class="tree-node"
        style={{ paddingLeft: (item.level - 1) * 20 + "px" }}
      >
        {item.children ? (
          item.open ? (
            <span class="icon" onClick={() => toggle(item)}>
              <IconOpen />
            </span>
          ) : (
            <span class="icon" onClick={() => toggle(item)}>
              <IconClose />
            </span>
          )
        ) : (
          <indent />
        )}
        <span>{item.label}</span>
      </div>
    );
    const renderTree = (data) => {
      return data.map((item) => renderNode(item));
      // return data.map((item) => {
      //   if (item.children) {
      //     return (
      //       <>
      //         {renderNode(item)}
      //         {renderTree(item.children)}
      //       </>
      //     );
      //   }
      //   return renderNode(item);
      // });
    };
    return () => <div>{renderTree(openedData)}</div>;
  }
});
